package com.bsoft.gol.hcb.dao.evaluation;

import ctd.account.UserRoleToken;
import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessAction;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import ctd.spring.boot.annotation.SsdevDao;
import ctd.util.annotation.RpcService;
import hcn.base.evaluation.EvaluationImpress;
import hcn.util.RpcUserToken;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.CriteriaSpecification;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by mlm on 2015/11/30.
 * <p/>
 * 满意度评价医生印象
 */
@SsdevDao(serviceId = "evaluationImpressDAOService")
public abstract class EvaluationImpressDAO extends HibernateSupportDelegateDAO<EvaluationImpress> {

    public EvaluationImpressDAO() {
        this.setKeyField("id");
    }

    /**
     * 查询医生印象
     *
     * @param doctorId
     * @param start
     * @param limit
     * @return
     */
    @RpcService
    @DAOMethod(sql = "select content,count(content) from EvaluationImpress where doctorId=:doctorId"
            + " and orgId in:orgIdList group by content order by count(content) desc")
    public abstract List<Object[]> findDoctImpresses(@DAOParam("doctorId") String doctorId, @DAOParam(pageStart = true) int start, @DAOParam(pageLimit = true) int limit,@DAOParam("orgIdList") List<String> orgIdList);

    /**
     * 查询医生印象
     *
     * @param doctorId
     * @return
     */
    @RpcService
    public List<Map<String, Object>> getDoctImpresses(final String doctorId, final int start, final int limit) {
        HibernateStatelessResultAction<List<Map<String, Object>>> action = new AbstractHibernateStatelessResultAction<List<Map<String, Object>>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuffer hsql = new StringBuffer();
                hsql.append("select content,count(content) as num from ods_evaluationimpress where doctor_id=:doctorId ");
                hsql.append(" and org_id in (select org_id from base_orgcloudmem where cloud_id=:tenantId) group by content order by count(content) desc");
                Query query = ss.createSQLQuery(hsql.toString());
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                query.setParameter("doctorId", doctorId);
                String tenantId = UserRoleToken.getCurrentTenantId();
                if (tenantId == null || tenantId.isEmpty()) {
                    tenantId = RpcUserToken.getTenantId();
                }
                query.setParameter("tenantId", tenantId);
                query.setFirstResult(start);
                query.setMaxResults(limit);
                List<Map<String, Object>> ls = (List<Map<String, Object>>) query.list();
                setResult(ls);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    /**
     * 查询医生印象
     *
     * @param doctorId
     * @return
     */
    @DAOMethod(sql = "select content from EvaluationImpress where doctorId=:doctorId "
            + " and orgId in:orgIdList group by content ")
    public abstract List<String[]> findContentsByDoctId(@DAOParam("doctorId") String doctorId,@DAOParam("orgIdList") List<String> orgIdList);

    /**
     * 查询用户添加医生印象次数
     *
     * @param userId
     * @return
     */
    @DAOMethod(sql = "select count(id) from EvaluationImpress where evaluateUserId=:userId and doctorId=:doctorId"
            + " and orgId in:orgIdList and businessId=:businessId ")
    public abstract long getCountByUserId(@DAOParam("userId") String userId, @DAOParam("doctorId") String doctorId, @DAOParam("businessId") int businessId,@DAOParam("orgIdList") List<String> orgIdList);

    /**
     * 保存医生印象
     *
     * @param map
     */
    public void saveImpresses(final Map<String, Object> map) {
        HibernateSessionTemplate.instance().executeTrans(new HibernateStatelessAction() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                String doctorId = "";
                if (map.get("doctorId") != null) {
                    doctorId = String.valueOf(map.get("doctorId"));
                }
                String userId = String.valueOf(map.get("userId"));
                String orgId = String.valueOf(map.get("orgId"));
                int businessId = Integer.parseInt(String.valueOf(map.get("businessId")));
                if (map.get("impressList") != null) {
                    Date date = Calendar.getInstance().getTime();
                    List<String> impressList = (List<String>) map.get("impressList");
                    if (impressList != null && impressList.size() > 0) {
                        for (String impress : impressList) {
                            EvaluationImpress entity = new EvaluationImpress();
                            entity.setContent(impress);
                            entity.setCreateDt(date);
                            entity.setDoctorId(doctorId);
                            entity.setEvaluateUserId(userId);
                            entity.setOrgId(orgId);
                            entity.setBusinessId(businessId);
                            entity.setTenantId(UserRoleToken.getCurrentTenantId());
                            ss.insert(entity);
                        }
                    }
                }
            }
        });
    }
}
